<template>
	<view class="page-container">
		<view class="header-box" :style="{ paddingTop: winInfo.top + 'px' }">
			<view class="header-info">
				<tui-icon name="arrowleft" @tap="goBack" color="#333333" size="25" bold="true"></tui-icon>
				<view class="header-name">
					<image :src="userInfo.Avatar || '/static/images/my/noAvatar.svg'" class="avatar-img" mode="aspectFill"></image>
					<view class="user-info">
						<view>{{ userInfo.Name || userInfo.Account }}</view>
						<view class="time-info">{{ computeTime(userInfo.lastTime) }}</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 消息列表 -->
		<scroll-view scroll-y="true" @scrolltoupper="onScrollToUpper" :scroll-top="scrollTop" :scroll-with-animation="true" class="scroll-view">
			<view class="message-container" ref="messageContainer">
				<view v-for="(item, index) in messageList" :key="index">
					<!-- 时间显示 -->
					<view v-if="showMessageTime(index)" class="message-time">
						{{ formatMessageTime(item.CreateTime) }}
					</view>
					<view class="message-box" :style="{ justifyContent: item.YonghuID == CurrentUser.Id ? 'flex-end' : 'flex-start' }">
						<image v-if="item.YonghuID != CurrentUser.Id" :src="userInfo.Avatar" mode="aspectFill" class="user-avatr"></image>
						<view class="message-info" v-if="item.Leixing == '文字'">
							{{ item.Xinxi }}
						</view>
						<view class="message-info message-info-voice" v-else-if="item.Leixing === '语音'" @tap="playVoice(item)">
							<view
								class="audio-icon-container"
								v-if="item.YonghuID !== CurrentUser.Id"
								:class="{ reserve: item.YonghuID == CurrentUser.Id, 'is-playing': currentPlayingVoice === item.ID }"
							>
								<image src="/static/images/message/msgaudio1.png" class="audio-icon" :class="{ reserve: item.YonghuID == CurrentUser.Id }" mode="widthFix"></image>
								<image src="/static/images/message/msgaudio2.png" class="audio-icon" :class="{ reserve: item.YonghuID == CurrentUser.Id }" mode="widthFix"></image>
								<image src="/static/images/message/msgaudio3.png" class="audio-icon" :class="{ reserve: item.YonghuID == CurrentUser.Id }" mode="widthFix"></image>
							</view>
							<view class="voice-duration" :style="{ width: `${item.YuyinSC * 5 || 5}rpx` }">{{ item.YuyinSC || 1 }}"</view>
							<view
								class="audio-icon-container"
								v-if="item.YonghuID == CurrentUser.Id"
								:class="{ reserve: item.YonghuID == CurrentUser.Id, 'is-playing': currentPlayingVoice === item.ID }"
							>
								<image src="/static/images/message/msgaudio1.png" class="audio-icon" :class="{ reserve: item.YonghuID == CurrentUser.Id }" mode="widthFix"></image>
								<image src="/static/images/message/msgaudio2.png" class="audio-icon" :class="{ reserve: item.YonghuID == CurrentUser.Id }" mode="widthFix"></image>
								<image src="/static/images/message/msgaudio3.png" class="audio-icon" :class="{ reserve: item.YonghuID == CurrentUser.Id }" mode="widthFix"></image>
							</view>
						</view>
						<view v-else-if="item.Leixing == '卡片' && item.WenzhangInfo" @tap="wenzhangDetail(item)">
							<view class="message-info" style="padding: 0" v-if="item.Biaoming != 'sys_user'">
								<image
									v-if="item.WenzhangInfo && item.WenzhangInfo.logo"
									style="width: 500rpx"
									class="biji-image"
									:src="item.WenzhangInfo.logo"
									mode="widthFix"
								></image>
								<view v-else-if="item.WenzhangInfo.Shipin" style="position: relative">
									<view class="play-btn">
										<tui-icon name="turningright" color="#fff" size="20"></tui-icon>
									</view>
									<image
										v-if="item.WenzhangInfo.Fengmian"
										:src="Microi.FileServer + item.WenzhangInfo.Fengmian"
										mode="aspectFill"
										class="biji-image"
										style="max-height: 500rpx"
									></image>
								</view>

								<image
									v-else-if="item.WenzhangInfo.TupianMS"
									class="biji-image"
									style="width: 500rpx; height: 400rpx"
									:src="JSON.parse(item.WenzhangInfo.TupianMS)[0].url"
									mode="aspectFill"
								></image>
								<view class="no-img-box" v-else style="width: 500rpx">
									<image src="/static/images/find/douhao.png" mode="widthFix" class="douhao-img"></image>
									<view class="no-img-nr">
										{{ item.Xinxi }}
									</view>
									<view class="bottom-bgc"></view>
								</view>
								<view class="info-box" style="text-align: left">
									{{ item.Xinxi }}
								</view>
								<view class="Chatlog-user-info">
									<image v-if="item.Biaoming == 'diy_Biji'" :src="item.WenzhangInfo.Avatar || '/static/images/my/noAvatar.svg'" mode="aspectFill"></image>
									<image v-else src="/static/images/company/niming.png" mode="aspectFill"></image>
									<view>{{ item.Biaoming == 'diy_Biji' ? item.WenzhangInfo.Name : '匿名用户' }}</view>
								</view>
							</view>
							<view v-else class="user-share">
								<image :src="item.WenzhangInfo.BeijingT" mode="aspectFill" class="user-beijingt"></image>
								<view class="user-share-info">
									<image :src="item.WenzhangInfo.Avatar" mode="aspectFill" class="user-avatr"></image>
									<view class="user-Name">
										{{ item.WenzhangInfo.Name }}
									</view>
									<view class="fans-count">笔记·{{ item.WenzhangInfo.bijiCount }} ｜ 粉丝·{{ item.WenzhangInfo.fansCount || 0 }}</view>
									<view class="user-toLook">去看看</view>
								</view>
							</view>
						</view>
						<view class="message-info" style="padding: 0" v-else-if="item.Leixing == '视频'">
							<video :src="item.ShipinWJ" controls></video>
						</view>
						<view class="message-info" style="padding: 0" @tap="lookPicture(item.TupianNR)" v-else-if="item.Leixing == '图片'">
							<image :src="item.TupianNR" mode="aspectFill"></image>
						</view>
						<image v-if="item.YonghuID == CurrentUser.Id" :src="CurrentUser.Avatar" mode="aspectFill" class="user-avatr"></image>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- <button @click="sendMessage">发送</button> -->
		<view class="button-container" :style="{ bottom: winInfo.safeAreaInsets.bottom + 'px' }">
			<view class="input-box">
			<!-- 	<view class="voice-btn" @touchstart="startRecord" @touchend="stopRecord" @touchcancel="cancelRecord">
					<tui-icon :name="isRecording ? 'voice-fill' : 'voice'" color="#999" size="25"></tui-icon>
				</view> -->
				<input type="text" v-model="MessageInfo" placeholder="请输入消息" @confirm="sendMessage" class="message-input" :adjust-position="true" :focus="false" />
				<!-- <tui-icon name="imface" color="#999" size="25"></tui-icon> -->
				<tui-icon name="add" color="#999" size="25" @tap="showMoreInput"></tui-icon>
			</view>
			<view class="caozuo-container" v-if="moreInputModal">
				<view class="mask" @tap="moreInputModal = false"></view>
				<view class="caozuo-btn" @tap="inputCaozuo(1)">
					<view class="caozuo-img">
						<tui-icon name="camera-fill" color="#555" size="25"></tui-icon>
					</view>

					<view>拍照</view>
				</view>
				<view class="caozuo-btn" @tap="inputCaozuo(2)">
					<view class="caozuo-img">
						<tui-icon name="pic-fill" color="#555" size="25"></tui-icon>
					</view>
					<view>图片</view>
				</view>
				<view class="caozuo-btn" @tap="inputCaozuo(3)">
					<view class="caozuo-img">
						<tui-icon name="video" color="#555" size="25"></tui-icon>
					</view>
					<view>视频</view>
				</view>
				<view class="caozuo-btn" @tap="inputCaozuo(4)">
					<view class="caozuo-img">
						<tui-icon name="camera-fill" color="#555" size="25"></tui-icon>
					</view>
					<view>录制</view>
				</view>
			</view>
		</view>
		<!-- 录音提示 -->
		<view class="record-tip" v-if="isRecording">
			<view class="record-tip-content">
				<view class="record-tip-icon"></view>
				<view class="record-tip-text">松开发送</view>
			</view>
		</view>
	</view>
</template>

<script>
import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
import { TUIConversationService } from '@tencentcloud/chat-uikit-engine';
import { uploadFile } from '@/utils/tool.js';
export default {
	data() {
		return {
			Islogin: this.Microi.IsLogin(),
			CurrentUser: this.Microi.GetCurrentUser(),
			userInfo: {},
			winInfo: {
				height: 64, //header高度
				top: 26, //标题图标距离顶部距离
				scrollH: 0 //滚动总高度
			},
			startTime: 0,
			options: {},
			MessageInfo: '',
			chat: {},
			messageList: [],
			page: 1,
			noData: false,
			moreInputModal: false,
			isCompleted: false,
			nextReqMessageID: '',
			timeInterval: 10 * 60 * 1000, // 10分钟（秒为单位）
			lastShowTime: 0, // 记录最后显示的时间
			messageListener: null, // 存储消息监听器
			isRecording: false, // 是否正在录音
			recorderManager: null, // 录音管理器
			currentPlayingVoice: '', // 当前正在播放的语音ID
			innerAudioContext: null, // 音频播放器
			voicePath: '', // 新增：存储录音文件路径
			recordStartTime: 0, // 新增：录音开始时间
			recordDuration: 0, // 新增：录音时长
			audioMap: new Map(), // 新增：存储音频上下文
			isPlaying: false, // 新增：控制语音播放动画状态
			scrollTop: 0,
			scrollViewHeight: 0
		};
	},
	mounted() {
		let obj = {};
		// #ifdef MP-WEIXIN
		obj = wx.getMenuButtonBoundingClientRect();
		// #endif
		// #ifdef MP-BAIDU
		obj = swan.getMenuButtonBoundingClientRect();
		// #endif
		// #ifdef MP-ALIPAY
		my.hideAddToDesktopMenu();
		// #endif
		// #ifdef APP-PLUS
		// App端直接用系统信息
		obj = {};
		// #endif

		setTimeout(() => {
			uni.getSystemInfo({
				success: (res) => {
					this.winInfo = res;
					// #ifdef APP-PLUS
					this.winInfo.width = res.windowWidth;
					this.winInfo.height = res.statusBarHeight + 44;
					this.winInfo.top = res.statusBarHeight + 6;
					// #endif
					// #ifndef APP-PLUS
					this.winInfo.width = obj.left || res.windowWidth;
					this.winInfo.height = obj.top ? obj.top + obj.height + 8 : res.statusBarHeight + 44;
					this.winInfo.top = obj.top ? obj.top + (obj.height - 32) / 2 : res.statusBarHeight + 6;
					// #endif
					this.winInfo.scrollH = res.windowWidth;

					// 计算scroll-view的高度
					const query = uni.createSelectorQuery().in(this);
					query
						.select('.header-box')
						.boundingClientRect((data) => {
							const headerHeight = data ? data.height : 64;
							const bottomHeight = 180; // 底部输入框的高度
							// 兜底为窗口高度减去头部和底部
							this.scrollViewHeight = res.windowHeight - headerHeight - bottomHeight;
							console.log(this.scrollViewHeight);
							// if (!this.scrollViewHeight || this.scrollViewHeight < 100) {
							// 	this.scrollViewHeight = 500;
							// }
						})
						.exec();
				}
			});
		}, 0);

		// 初始化录音管理器
		this.initRecorder();
		// 初始化音频播放器
		this.initAudioPlayer();
	},

	onLoad(options) {
		this.options = options;
		this.getUserInfo();
		this.Imlogin();
	},
	onShow() {
		this.startTime = new Date();
	},
	onHide() {
		if (this.Islogin) {
			// 获取当前页面栈
			const pages = getCurrentPages();
			// 获取当前页面的对象
			const currentPage = pages[pages.length - 1];
			// 获取当前页面的路径
			const route = currentPage.route;
			// 获取当前页面的参数
			const options = currentPage.options;
			this.Microi.ApiEngine.Run('Add_liulanLog', {
				YemianCS: options,
				YemianDZ: route,
				LiulanSJC: new Date().getTime() - this.startTime.getTime()
			});
		}
	},
	watch() {
		var self = this;
		if (self.chat) {
			let onMessageReceived = function (event) {};
			self.chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
		}
	},
	onUnload() {
		if (this.Islogin) {
			// 获取当前页面栈
			const pages = getCurrentPages();
			// 获取当前页面的对象
			const currentPage = pages[pages.length - 1];
			// 获取当前页面的路径
			const route = currentPage.route;
			// 获取当前页面的参数
			const options = currentPage.options;
			this.Microi.ApiEngine.Run('Add_liulanLog', {
				YemianCS: options,
				YemianDZ: route,
				LiulanSJC: new Date().getTime() - this.startTime.getTime()
			});
		}
		// 移除消息监听器
		this.removeMessageListener();
		// 清理所有音频资源
		this.audioMap.forEach((audioContext) => {
			audioContext.destroy();
		});
		this.audioMap.clear();
	},
	methods: {
		sendMessage() {
			var self = this;
			let message = self.chat.createTextMessage({
				to: self.options.Account,
				conversationType: TencentCloudChat.TYPES.CONV_C2C,
				// 消息优先级，用于群聊。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息
				// priority: TencentCloudChat.TYPES.MSG_PRIORITY_NORMAL,
				payload: {
					text: self.MessageInfo
				},
				needReadReceipt: true
			});
			self.chatSendMessage(message);
			self.MessageInfo = '';
		},
		async Imlogin() {
			var self = this;
			let chat = TencentCloudChat.create({
				SDKAppID: 1600084585
			});
			chat.setLogLevel(0);
			chat.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });
			self.chat = chat;
			var UserSig = await this.Microi.ApiEngine.Run('get_Im_UserId', {
				Account: this.CurrentUser.Account
			});
			UserSig = UserSig.Data;
			let promise = chat.login({ userID: this.CurrentUser.Account, userSig: UserSig });
			promise
				.then(function (imResponse) {
					console.log(imResponse.data); // 登录成功
					if (imResponse.data.repeatLogin === true) {
						// 表示账号已登录，本次登录操作为重复登录
						console.log(imResponse.data.errorInfo);
					}
					let onSdkReady = function (event) {
						self.setupMessageListener();
					};
					chat.on(TencentCloudChat.EVENT.SDK_READY, onSdkReady);
				})
				.catch(function (imError) {
					console.warn('login error:', imError); // 错误信息
				});
		},
		// 设置消息监听器
		setupMessageListener() {
			const self = this;
			this.messageListener = function (event) {
				self.chatRoomRead();
				const messageList = event.data;
				messageList.forEach(async (message) => {
					var _RowModel = {
						UserId: self.options.YonghuID,
						CreateTime: new Date(message.time * 1000)
					};
					if (message.type == 'TIMTextElem') {
						_RowModel.Xinxi = message.payload.text;
						_RowModel.Leixing = '文字';
					} else if (message.type == 'TIMImageElem') {
						_RowModel.TupianNR = message.payload.imageInfoArray[1].url;
						_RowModel.Leixing = '图片';
					} else if (message.type == 'TIMVideoFileElem') {
						_RowModel.ShipinWJ = message.payload.videoUrl;
						_RowModel.Leixing = '视频';
					} else if (message.type == 'TIMSoundElem') {
						_RowModel.ShipinWJ = message.payload.url;
						_RowModel.Leixing = '语音';
						_RowModel.YuyinSC = message.payload.second;
					}
					if (_RowModel.Leixing) {
						self.messageList.push(_RowModel);
					}

					self.messageList.sort((a, b) => new Date(a.CreateTime).getTime() - new Date(b.CreateTime).getTime());
					self.scrollToBottom();
					console.log(self.messageList);
				});
			};
			// 注册消息监听器
			this.chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, this.messageListener);
		},

		async chatSendMessage(message) {
			var self = this;
			let promise = self.chat.sendMessage(message);
			self.moreInputModal = false;
			promise
				.then(function (imResponse) {
					self.addChatlog(imResponse.data.message);
					self.scrollToBottom();
				})
				.catch(function (imError) {
					console.warn('sendMessage error:', imError);
				});
		},
		wenzhangDetail(item) {
			if (item.Biaoming == 'diy_GangweiPJ') {
				uni.navigateTo({
					url: '/pages/my/companyInfo/companyInfo?Id=' + item.WenzhangInfo.GongsiID + '&currentTab=0&WenZhangID=' + item.WenzhangID
				});
			} else if (item.Biaoming == 'diy_MianJing') {
				uni.navigateTo({
					url: '/pages/my/companyInfo/companyInfo?Id=' + item.WenzhangInfo.GongsiID + '&currentTab=1&WenZhangID=' + item.WenzhangID
				});
			} else if (item.Biaoming == 'diy_CompanyInfo') {
				uni.navigateTo({
					url: '/pages/my/companyInfo/companyInfo?Id=' + item.WenzhangID
				});
			} else if (item.Biaoming == 'diy_Biji') {
				if (item.WenzhangInfo.Shipin) {
					uni.navigateTo({
						url: '/pages/my/Biji/shipin?Id=' + item.WenzhangID
					});
				} else {
					uni.navigateTo({
						url: '/pages/my/Biji/tuwen?Id=' + item.WenzhangID
					});
				}
			} else if (item.Biaoming == 'sys_user') {
				uni.navigateTo({
					url: '/pages/my/myDetail/myDetail?Id=' + item.WenzhangID
				});
			}
		},
		async addChatlog(message) {
			var self = this;
			var _RowModel = {
				FasongR: self.CurrentUser.Account,
				YonghuID: self.CurrentUser.Id,
				ShouxinR: self.options.conversationID,
				ShouxinRID: self.options.YonghuID,
				TupianNR: '',
				Xinxi: '',
				ShipinWJ: '',
				Yidu: 0,
				FasongRSC: 0,
				ShouxinRSC: 0,
				LiaotianSID: this.options.ChatRoomId
			};
			if (message.type == 'TIMTextElem') {
				_RowModel.Xinxi = message.payload.text;
				_RowModel.Leixing = '文字';
			} else if (message.type == 'TIMImageElem') {
				var res = await self.uploadImage(message.payload.imageInfoArray[1].url);
				_RowModel.TupianNR = res.url;
				_RowModel.Leixing = '图片';
			} else if (message.type == 'TIMVideoFileElem') {
				var res = await self.uploadFile(message.payload.videoUrl);
				_RowModel.ShipinWJ = res.url;
				_RowModel.Leixing = '视频';
			} else if (message.type == 'TIMSoundElem') {
				var res = await self.uploadFile(message.payload.url);
				_RowModel.ShipinWJ = res.url;
				_RowModel.YuyinSC = message.payload.second;
				_RowModel.Leixing = '语音';
			}
			setTimeout(async function () {
				var res = await self.Microi.ApiEngine.Run('add_ChatLog', {
					_RowModel: _RowModel
				});
				// var res = await self.Microi.FormEngine.AddFormData({
				// 	FormEngineKey: 'diy_ChatLog',
				// 	_RowModel: _RowModel
				// });
				self.messageList.push(res.Data);
				self.messageList.sort((a, b) => new Date(a.CreateTime).getTime() - new Date(b.CreateTime).getTime());
			}, 0);
		},
		showMoreInput() {
			this.moreInputModal = true;
		},
		chatRoomRead() {
			var self = this;
			var res = self.Microi.ApiEngine.Run('ChatLog_readOnly', {
				ChatRoomId: self.options.ChatRoomId,
				YonghuID: self.options.YonghuID
			});
		},
		inputCaozuo(index) {
			var self = this;
			var message = {};
			if (index == 1) {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera'], //从相册选择
					success: async function (res) {
						// var result = await self.uploadImage(res.tempFilePaths[0]);
						// console.log(result, 'res', res);
						message = self.chat.createImageMessage({
							to: self.options.Account,
							conversationType: TencentCloudChat.TYPES.CONV_C2C,
							payload: {
								file: res
							},
							needReadReceipt: true,
							onProgress: function (event) {
								console.log('file uploading:', event);
							}
						});
						console.log(message, 'message');
						// 2. 发送消息
						self.chatSendMessage(message);
					}
				});
			} else if (index == 2) {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: async function (res) {
						// var result = await self.uploadImage(res.tempFilePaths[0]);
						// console.log(result, 'res', res);
						message = self.chat.createImageMessage({
							to: self.options.Account,
							conversationType: TencentCloudChat.TYPES.CONV_C2C,
							payload: {
								file: res
							},
							needReadReceipt: true,
							onProgress: function (event) {
								console.log('file uploading:', event);
							}
						});
						console.log(message, 'message');
						// 2. 发送消息
						self.chatSendMessage(message);
					}
				});
			} else if (index == 3) {
				uni.chooseMedia({
					count: 1,
					mediaType: ['video'],
					sourceType: ['album'],
					camera: 'back',
					success(res) {
						message = self.chat.createVideoMessage({
							to: self.options.Account,
							conversationType: TencentCloudChat.TYPES.CONV_C2C,
							payload: {
								file: res
							},
							needReadReceipt: true,
							onProgress: function (event) {
								console.log('file uploading:', event);
							}
						});
						self.chatSendMessage(message);
					}
				});
			} else if (index == 4) {
				uni.chooseMedia({
					count: 1,
					mediaType: ['video'],
					sourceType: ['camera'],
					camera: 'back',
					success(res) {
						message = self.chat.createVideoMessage({
							to: self.options.Account,
							conversationType: TencentCloudChat.TYPES.CONV_C2C,
							payload: {
								file: res
							},
							needReadReceipt: true,
							onProgress: function (event) {
								console.log('file uploading:', event);
							}
						});
						self.chatSendMessage(message);
					}
				});
			}
		},
		lookPicture(url) {
			uni.previewImage({
				urls: [url],
				current: 0
			});
		},
		computeTime(Time) {
			Time = new Date(Time);
			var passTime = new Date().getTime() - Time.getTime();
			if (passTime < 24 * 1000 * 60 * 60) {
				return '今天在线';
			} else if (passTime / 24 / 1000 / 60 / 60 < 7) {
				return `${parseInt(passTime / 24 / 1000 / 60 / 60)}天内在线`;
			} else {
				return '7天以上在线';
			}
		},
		showMessageTime(index) {
			if (index === 0) {
				this.lastShowTime = this.messageList[0].CreateTime;
				return true;
			}

			const currentMessage = this.messageList[index];
			const previousMessage = this.messageList[index - 1];
			const timeDiff = new Date(currentMessage.CreateTime).getTime() - new Date(previousMessage.CreateTime).getTime();

			// 如果当前消息时间距离上一条消息时间超过10分钟，显示新时间
			if (timeDiff >= this.timeInterval) {
				this.lastShowTime = new Date(currentMessage.CreateTime);
				return true;
			}
			return false;
		},
		formatMessageTime(time) {
			const now = new Date().getTime(); // 当前时间戳（秒）
			const messageDate = new Date(time);
			const diff = now - messageDate.getTime(); // 时间差（秒）
			var Year = new Date(messageDate).getFullYear();
			var month = new Date(messageDate).getMonth() + 1;
			month = month < 10 ? '0' + month : month;
			var day = new Date(messageDate).getDate();
			day = day < 10 ? '0' + day : day;
			var hours = new Date(messageDate).getHours();
			hours = hours < 10 ? '0' + hours : hours;
			var miniutes = new Date(messageDate).getMinutes();
			miniutes = miniutes < 10 ? '0' + miniutes : miniutes;
			// 今天的消息
			if (diff < 24 * 60 * 60 * 1000) {
				return hours + ':' + miniutes;
			}
			// 昨天的消息
			else if (diff < 48 * 60 * 60 * 1000) {
				return '昨天 ' + hours + ':' + miniutes;
			}
			// 一周内的消息
			else {
				return Year + '-' + month + '-' + day + ' ' + hours + ':' + miniutes;
			}
		},
		scrollToBottom() {
			this.$nextTick(() => {
				// #ifdef APP-PLUS
				// App端用pageScrollTo兜底
				setTimeout(() => {
					uni.pageScrollTo({
						scrollTop: 9999999999999999999999999999,
						duration: 0
					});
				}, 100);
				// #endif

				// 其它端用scrollTop
				const query = uni.createSelectorQuery().in(this);
				query
					.select('.message-container')
					.boundingClientRect((data) => {
						if (data) {
							setTimeout(() => {
								this.scrollTop = data.height;
							}, 50);
						}
					})
					.exec();
			});
		},

		// 上拉加载更多聊天记录
		onScrollToUpper() {
			this.loadMoreHistory();
		},
		async loadMoreHistory() {
			if (this.noData) return;
			const query = uni.createSelectorQuery().in(this);
			query
				.select('.message-container')
				.boundingClientRect((data) => {
					const oldHeight = data ? data.height : 0;
					this.getHitroyList().then(() => {
						this.$nextTick(() => {
							query
								.select('.message-container')
								.boundingClientRect((newData) => {
									const newHeight = newData ? newData.height : 0;
									this.scrollTop += newHeight - oldHeight;
								})
								.exec();
						});
					});
				})
				.exec();
		},

		// 修改getHitroyList为返回Promise
		async getHitroyList() {
			var self = this;
			console.log(11111111111);
			if (self.noData) return Promise.resolve();
			return self.Microi.ApiEngine.Run('get_ChatList', {
				myId: self.CurrentUser.Id,
				YonghuID: self.options.YonghuID,
				page: self.page,
				ChatRoomId: self.options.ChatRoomId
			}).then((res) => {
				console.log(res.Data);
				if (!res.Data.length) {
					self.noData = true;
					return;
				}
				self.messageList.unshift(...res.Data);
				self.messageList.sort((a, b) => new Date(a.CreateTime).getTime() - new Date(b.CreateTime).getTime());
				self.page++;
			});
		},
		async getUserInfo() {
			var self = this;
			var res = await self.Microi.ApiEngine.Run('get_ChatRoomInfo', {
				YonghuID: self.options.YonghuID,
				myId: self.CurrentUser.Id
			});
			if (res.Code != 1) {
				this.Microi.Tips(res.Msg, false);
				setTimeout(function () {
					self.goBack();
				}, 1000);
			} else {
				this.userInfo = res.Data.UserInfo;
				this.options.ChatRoomId = res.Data.ChatRoom.Id;
				await self.getHitroyList();
				// 确保消息加载完成后再滚动到底部
				setTimeout(() => {
					self.scrollToBottom();
				}, 1000);
			}
		},
		goBack() {
			let pages = getCurrentPages(); // 获取当前页面堆栈
			let pageCount = pages.length; // 页面堆栈中的页面数量
			// 判断是否有上级页面
			if (pageCount > 1) {
				// 如果有上级页面，则返回上级页面
				uni.navigateBack({
					delta: 1
				});
			} else {
				// 如果没有上级页面，则返回首页
				uni.switchTab({
					url: '/pages/tabbar/find/find' // 替换为你的首页路径
				});
			}
		},
		// 初始化录音管理器
		initRecorder() {
			var self = this;
			if (!this.recorderManager) {
				this.recorderManager = uni.getRecorderManager();

				// 监听录音开始事件
				this.recorderManager.onStart(() => {
					console.log('录音开始');
					this.recordStartTime = Date.now();
				});

				// 监听录音错误事件
				this.recorderManager.onError((errMsg) => {
					console.warn('recorder error:', errMsg);
					this.isRecording = false;
					uni.showToast({
						title: '录音失败',
						icon: 'none'
					});
				});

				// 监听录音结束事件
				this.recorderManager.onStop(async (res) => {
					console.log('recorder stop', res);
					this.isRecording = false;
					this.recordDuration = Math.floor((Date.now() - this.recordStartTime) / 1000);

					// var result = await self.uploadFile(res.tempFilePath);
					// console.log(res, 'res', this.recordDuration);
					this.voicePath = res.tempFilePath;
					// res.tempFilePath = result.url;
					// 检查录音时长是否小于1秒
					if (this.recordDuration < 1) {
						uni.showToast({
							title: '录音时间太短',
							icon: 'none'
						});
						return;
					}
					// 创建音频消息
					const message = this.chat.createAudioMessage({
						to: this.options.Account,
						conversationType: TencentCloudChat.TYPES.CONV_C2C,
						payload: {
							file: res,
							second: this.recordDuration
						}
					});

					// 发送消息
					this.chatSendMessage(message);
				});

				// 监听录音帧数据
				this.recorderManager.onFrameRecorded((res) => {
					const { frameBuffer, isLastFrame } = res;
				});
			}
		},

		// 开始录音
		startRecord(e) {
			// 检查是否正在播放语音
			if (this.currentPlayingVoice) {
				this.innerAudioContext.stop();
				this.currentPlayingVoice = '';
			}

			this.isRecording = true;

			// 录音参数
			const recordOptions = {
				duration: 60000, // 最长录音时间，单位ms
				sampleRate: 44100, // 采样率
				numberOfChannels: 1, // 录音通道数
				encodeBitRate: 192000, // 编码码率
				// #ifdef MP-WEIXIN
				format: 'aac', // 微信小程序用aac
				// #endif
				// #ifdef APP-PLUS
				format: 'mp3', // App端用mp3
				// #endif
				frameSize: 1 // 指定帧大小
			};

			// 开始录音
			this.recorderManager.start(recordOptions);
		},

		// 停止录音
		stopRecord(e) {
			if (this.isRecording) {
				this.recorderManager.stop();
			}
		},

		// 取消录音
		cancelRecord(e) {
			if (this.isRecording) {
				this.isRecording = false;
				this.recorderManager.stop();
				uni.showToast({
					title: '已取消录音',
					icon: 'none'
				});
			}
		},

		// 播放语音
		playVoice(message) {
			// 如果正在播放同一个语音，则停止播放
			if (this.currentPlayingVoice === message.ID) {
				this.stopAudio();
				return;
			}

			// 如果正在播放其他语音，先停止
			if (this.currentPlayingVoice) {
				this.stopAudio();
			}

			// 开始播放新的语音
			this.currentPlayingVoice = message.ID;

			// 获取或创建音频上下文
			let audioContext = this.audioMap.get(message.ID);
			if (!audioContext) {
				audioContext = uni.createInnerAudioContext();
				this.audioMap.set(message.ID, audioContext);

				// 设置音频事件监听
				audioContext.onPlay(() => {
					console.log('开始播放音频');
				});

				audioContext.onStop(() => {
					console.log('停止播放音频');
					this.currentPlayingVoice = '';
				});

				audioContext.onEnded(() => {
					console.log('播放结束');
					this.currentPlayingVoice = '';
				});

				audioContext.onError((res) => {
					console.error('音频播放错误:', res);
					this.currentPlayingVoice = '';
					uni.showToast({
						title: '播放失败',
						icon: 'none'
					});
				});
			}

			// 直接播放音频URL
			audioContext.src = message.ShipinWJ;
			audioContext.play();
		},
		async uploadFile(Path) {
			uni.showLoading({
				title: '上传中',
				mask: true
			});
			var res = await this.Microi.Upload({
				Path: '/file', // 文件路径前缀
				Limit: false, // 是否上传到私有存储桶
				Preview: 'true', // 是否压缩图片
				_FilePath: Path
			});
			uni.hideLoading();
			if (res.Code == 1) {
				var obj = {
					Path: res.Data.Path,
					Name: res.Data.Name,
					Size: res.Data.Size,
					CreateTime: res.Data.CreateTime,
					Id: res.Data.Id,
					url: this.GetServerPath(res.Data.Path),
					name: res.Data.Name,
					extname: res.Data.Path.split('.')[1]
				};

				return obj;
			}
		},
		GetServerPath(Path) {
			if (!Path) {
				return '';
			}
			return this.Microi.FileServer + Path;
		},
		// 停止音频播放
		stopAudio() {
			if (this.currentPlayingVoice) {
				const audioContext = this.audioMap.get(this.currentPlayingVoice);
				if (audioContext) {
					audioContext.stop();
				}
				this.currentPlayingVoice = '';
			}
		},

		// 初始化音频播放器
		initAudioPlayer() {
			if (!this.innerAudioContext) {
				this.innerAudioContext = uni.createInnerAudioContext();

				// 监听播放结束
				this.innerAudioContext.onEnded(() => {
					this.currentPlayingVoice = '';
				});

				// 监听播放错误
				this.innerAudioContext.onError((res) => {
					console.error('音频播放错误:', res);
					this.currentPlayingVoice = '';
					uni.showToast({
						title: '播放失败',
						icon: 'none'
					});
				});

				// 监听播放开始
				this.innerAudioContext.onPlay(() => {
					console.log('开始播放音频');
				});

				// 监听播放暂停
				this.innerAudioContext.onPause(() => {
					console.log('暂停播放音频');
				});

				// 监听播放停止
				this.innerAudioContext.onStop(() => {
					console.log('停止播放音频');
					this.currentPlayingVoice = '';
				});
			}
		},

		// 格式化语音时长
		formatVoiceDuration(duration) {
			return duration;
		},
		async SelectImage(e, name) {
			uni.showLoading({
				title: '上传照片中',
				mask: true
			});
			var array = e.tempFilePaths;
			array.forEach(async (item) => {
				var res = await this.uploadImage(item);
				this.FormData[name].push(res);
			});
			setTimeout(function () {
				uni.hideLoading();
			}, 1000);
		},
		deleteImage(e, name) {
			const index = this.FormData[name].findIndex((item) => item.Url == e.url);
			if (index > -1) {
				this.FormData[name].splice(index, 1);
			}
		},
		async uploadImage(Path) {
			var res = await this.Microi.Upload({
				Path: '/img', // 文件路径前缀
				Limit: false, // 是否上传到私有存储桶
				Preview: true, // 是否压缩图片
				_FilePath: Path
			});
			if (res.Code == 1) {
				var obj = {
					Path: res.Data.Path,
					Name: res.Data.Name,
					Size: res.Data.Size,
					CreateTime: res.Data.CreateTime,
					Id: res.Data.Id,
					url: this.GetServerPath(res.Data.Path),
					name: res.Data.Name,
					extname: res.Data.Path.split('.')[1]
				};
				return obj;
			}
		},
		GetServerPath(Path) {
			if (!Path) {
				return '';
			}
			return this.Microi.FileServer + Path;
		}
	}
	// onPullDownRefresh() {
	// 	this.getHitroyList();
	// 	setTimeout(function () {
	// 		uni.stopPullDownRefresh();
	// 	}, 500);
	// }
};
</script>

<style>
page {
	background-color: #fff;
}
.page-container {
	padding: 180rpx 20rpx 180rpx 20rpx;
	color: #000;
	box-sizing: border-box;
	min-height: 100vh;
	position: relative;
}

.header-box {
	width: 100%;
	position: fixed;
	left: 0;
	top: 0;
	z-index: 999;
	background-color: #fff;
	display: flex;
	align-items: center;
	justify-content: space-between;
	box-sizing: border-box;
	border-bottom: 2rpx solid #eef0f1;
	padding-bottom: 8rpx;
}
.header-name {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 12rpx;
	font-family: PingFang SC, PingFang SC;
	font-weight: 800;
	font-size: 28rpx;
	color: #212121;
	text-align: left;
	font-style: normal;
	text-transform: none;
}
.avatar-img {
	width: 76rpx;
	height: 76rpx;
	border-radius: 50%;
}
.header-info {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 20rpx;
}
.header-btn {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 20rpx;
}
.header-btn image {
	width: 44rpx;
	height: 44rpx;
}
.hearder-container {
	padding: 20rpx 0;
	border-bottom: 2rpx solid #f4f5f6;
}
.user-info {
	display: flex;
	justify-content: flex-start;
	flex-direction: column;
	gap: 8rpx;
}
.time-info {
	font-family: PingFang SC, PingFang SC;
	font-weight: 800;
	font-size: 24rpx;
	color: #999999;
	text-align: left;
	font-style: normal;
	text-transform: none;
}
.message-container {
	display: flex;
	justify-content: flex-start;
	flex-direction: column;
	gap: 20rpx;
	padding-bottom: 20rpx;
	box-sizing: border-box;
}
.message-box {
	display: flex;
	justify-content: flex-start;
	gap: 18rpx;
}
.user-avatr {
	width: 76rpx;
	height: 76rpx;
	border-radius: 50%;
}
.message-info {
	padding: 20rpx 28rpx;
	box-sizing: border-box;
	background: #f6f6f6;
	border-radius: 16rpx 16rpx 16rpx 16rpx;
	max-width: 500rpx;

	font-family: PingFang SC, PingFang SC;
	font-size: 28rpx;
	color: #212121;
	text-align: left;
	font-style: normal;
	text-transform: none;
	overflow: hidden;
}
.message-info video {
	width: 250rpx;
	z-index: 0;
}
.message-info image {
	width: 250rpx;
	z-index: 0;
}
.play-btn {
	position: absolute;
	top: 22rpx;
	right: 22rpx;
	width: 48rpx;
	height: 48rpx;
	border-radius: 50%;
	z-index: 990;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: rgba(0, 0, 0, 0.1);
}
.LiuLanL-box {
	position: absolute;
	left: 3%;
	top: 1%;
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 2rpx;

	font-family: Roboto, Roboto;
	font-size: 28rpx;
	color: #ffffff;
	text-align: left;
	font-style: normal;
	text-transform: none;
	padding: 2rpx 10rpx;
	border-radius: 30rpx;
	background-color: rgba(0, 0, 0, 0.1);
}
.LiuLanL-box image {
	width: 32rpx;
	height: 32rpx;
}
.biji-image {
	width: 100%;
	background-color: #fff;
}

.no-img-box {
	width: 500rpx;
	height: 500rpx;
	background: #ede7fb;
	position: relative;

	display: flex;
	align-items: center;
	justify-content: center;
	text-align: center;
	padding: 20rpx;
	box-sizing: border-box;
}
.bottom-bgc {
	position: absolute;
	bottom: 5%;
	right: 5%;

	width: 50rpx;
	height: 20rpx;
	background-color: #dac8e9;
}
.Chatlog-user-info {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 16rpx;
	margin: 16rpx;

	font-family: PingFang SC, PingFang SC;
	font-size: 25rpx;
	color: #333333;
	text-align: center;
	font-style: normal;
	text-transform: none;
}
.Chatlog-user-info image {
	width: 30rpx;
	height: 30rpx;
	border-radius: 50%;
}
.info-box {
	width: 100%;
	padding: 10rpx;
	font-family: PingFang SC, PingFang SC;
	font-size: 28rpx;
	color: #333333;
	text-align: center;
	font-style: normal;
	text-transform: none;

	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 3;
	overflow: hidden;
	text-overflow: ellipsis;
	word-wrap: break-word;
}
.no-img-nr {
	width: 100%;
	height: 80rpx;
	font-family: PingFang SC, PingFang SC;
	font-weight: 500;
	font-size: 28rpx;
	color: #333333;
	text-align: center;
	font-style: normal;
	text-transform: none;

	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 3;
	overflow: hidden;
	text-overflow: ellipsis;
	word-wrap: break-word;
}
.douhao-img {
	position: absolute;
	top: 5%;
	left: 5%;
	width: 50rpx !important;
}
.button-container {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	background: #f6f6f8;
	padding: 20rpx;
	box-sizing: border-box;
	z-index: 10;
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}
.caozuo-container {
	padding: 16rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	flex-wrap: wrap;
}
.caozuo-container .mask {
	position: fixed;
	z-index: 800;
	width: 100vw;
	height: 100vh;
}
.caozuo-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;
	gap: 10rpx;
	color: #999;
	z-index: 999;
}
.caozuo-img {
	background-color: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100rpx;
	width: 100rpx;
	border-radius: 16rpx;
}
.button-container .input-box {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 20rpx;
	background: #fff;
	border-radius: 16rpx;
	padding: 0 22rpx;
	height: 88rpx;
}
.message-input {
	flex: 1;
	height: 88rpx;
	background: transparent;
	font-size: 28rpx;
}

.message-time {
	text-align: center;
	margin: 20rpx 0;
	font-size: 24rpx;
	color: #999;
}

.voice-btn {
	width: 50rpx;
	height: 50rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.record-tip {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	background: rgba(0, 0, 0, 0.6);
	border-radius: 10rpx;
	padding: 30rpx;
	z-index: 999;
}

.record-tip-content {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.record-tip-icon {
	width: 100rpx;
	height: 100rpx;
	background: #fff;
	border-radius: 50%;
	margin-bottom: 20rpx;
	animation: recording 1s infinite;
}

.record-tip-text {
	color: #fff;
	font-size: 28rpx;
}

@keyframes recording {
	0% {
		transform: scale(1);
		opacity: 1;
	}
	50% {
		transform: scale(1.2);
		opacity: 0.8;
	}
	100% {
		transform: scale(1);
		opacity: 1;
	}
}

.message-info-voice {
	min-width: 80rpx;
	max-width: 300rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background: #f6f6f6;
	border-radius: 16rpx;
	position: relative;
}

.audio-icon-container {
	width: 32rpx;
	height: 40rpx;
	position: relative;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	margin: 0 14rpx 0 0;
	overflow: visible;
}

.audio-icon-container image {
	width: 30rpx;
	height: 30rpx;
}

.audio-icon {
	width: 30rpx;
	height: 30rpx;
	position: absolute;
	opacity: 0;
	transition: opacity 0.3s ease;
}

.voice-duration {
	min-width: 40rpx;
	font-size: 24rpx;
	color: #999;
	text-align: start;
	white-space: nowrap;
	margin: 0 10rpx;
}

.message-info-voice.reserve {
	flex-direction: row-reverse;
}

.message-info-voice.reserve .audio-icon-container {
	margin: 0 0 0 14rpx;
}

.scroll-view {
	flex: 1;
	width: 100%;
	height: 80vh;
}
.user-share {
	width: 300rpx;
	border-radius: 20rpx;
	overflow: hidden;
	background-color: #f6f6f6;
	padding-bottom: 20rpx;
	box-sizing: border-box;
}
.user-beijingt {
	width: 100%;
	height: 100rpx;
}
.user-share-info {
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;
	gap: 8rpx;
	margin-top: -40rpx;
}
.user-Name {
	font-family: PingFang SC, PingFang SC;
	font-weight: 600;
	font-size: 25rpx;
	color: #333333;
	text-align: center;
	font-style: normal;
	text-transform: none;
}
.fans-count {
	font-family: PingFang SC, PingFang SC;
	font-size: 20rpx;
	color: #999;
	text-align: center;
	font-style: normal;
	text-transform: none;
}
.user-toLook {
	padding: 10rpx 16rpx;
	font-family: PingFang SC, PingFang SC;
	font-size: 20rpx;
	border-radius: 30rpx;
	color: #FB353B;
	border: 1rpx solid #FB353B;
	text-align: center;
	font-style: normal;
	text-transform: none;
}
</style>
